<template>
  <div class="order-management">
    <div class="page-header">
      <h2>订单管理</h2>
    </div>

    <div class="search-bar">
      <el-input
        v-model="searchQuery"
        placeholder="搜索订单号或会员信息"
        style="width: 300px"
        clearable
        @input="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
    </div>

    <el-table :data="filteredOrders" style="width: 100%" v-loading="loading">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="orderNumber" label="订单号" width="150" />
      <el-table-column prop="memberName" label="会员" width="120" />
      <el-table-column prop="totalAmount" label="总金额" width="120">
        <template #default="scope">
          ¥{{ scope.row.totalAmount.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column prop="discountAmount" label="折扣" width="100">
        <template #default="scope">
          ¥{{ scope.row.discountAmount.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column prop="finalAmount" label="实付金额" width="120">
        <template #default="scope">
          ¥{{ scope.row.finalAmount.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button size="small" @click="viewOrderDetail(scope.row)">查看详情</el-button>
          <el-button 
            size="small" 
            type="success" 
            v-if="scope.row.status === 'PENDING'"
            @click="completeOrder(scope.row.id)"
          >
            完成订单
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 订单详情对话框 -->
    <el-dialog
      v-model="showDetailDialog"
      title="订单详情"
      width="800px"
    >
      <div v-if="selectedOrder" class="order-detail">
        <div class="order-info">
          <h3>订单信息</h3>
          <p><strong>订单号：</strong>{{ selectedOrder.orderNumber }}</p>
          <p><strong>会员：</strong>{{ selectedOrder.memberName || '非会员' }}</p>
          <p><strong>状态：</strong>{{ getStatusText(selectedOrder.status) }}</p>
          <p><strong>创建时间：</strong>{{ selectedOrder.createTime }}</p>
        </div>
        
        <div class="order-items">
          <h3>商品清单</h3>
          <el-table :data="selectedOrder.items" style="width: 100%">
            <el-table-column prop="productName" label="商品名称" />
            <el-table-column prop="quantity" label="数量" width="100" />
            <el-table-column prop="unitPrice" label="单价" width="100">
              <template #default="scope">
                ¥{{ scope.row.unitPrice.toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column prop="totalPrice" label="小计" width="100">
              <template #default="scope">
                ¥{{ scope.row.totalPrice.toFixed(2) }}
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <div class="order-summary">
          <p><strong>总金额：</strong>¥{{ selectedOrder.totalAmount.toFixed(2) }}</p>
          <p><strong>折扣金额：</strong>¥{{ selectedOrder.discountAmount.toFixed(2) }}</p>
          <p><strong>实付金额：</strong>¥{{ selectedOrder.finalAmount.toFixed(2) }}</p>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'

export default {
  name: 'OrderManagement',
  components: {
    Search
  },
  setup() {
    const loading = ref(false)
    const orders = ref([])
    const filteredOrders = ref([])
    const searchQuery = ref('')
    const showDetailDialog = ref(false)
    const selectedOrder = ref(null)

    const loadOrders = async () => {
      loading.value = true
      try {
        const response = await fetch('/api/orders')
        const data = await response.json()
        orders.value = data
        filteredOrders.value = data
      } catch (error) {
        ElMessage.error('加载订单数据失败')
        // 使用模拟数据
        orders.value = [
          {
            id: 1,
            orderNumber: 'ORD001',
            memberName: '张三',
            totalAmount: 25.50,
            status: '已完成',
            createTime: '2024-01-15 14:30:00',
            items: [
              { productName: '可口可乐', quantity: 2, price: 3.50, subtotal: 7.00 },
              { productName: '康师傅方便面', quantity: 1, price: 4.50, subtotal: 4.50 }
            ]
          },
          {
            id: 2,
            orderNumber: 'ORD002',
            memberName: '李四',
            totalAmount: 18.00,
            status: '处理中',
            createTime: '2024-01-15 16:20:00',
            items: [
              { productName: '农夫山泉', quantity: 3, price: 2.00, subtotal: 6.00 },
              { productName: '面包', quantity: 2, price: 6.00, subtotal: 12.00 }
            ]
          }
        ]
        filteredOrders.value = orders.value
      } finally {
        loading.value = false
      }
    }

    const handleSearch = () => {
      if (!searchQuery.value) {
        filteredOrders.value = orders.value
      } else {
        filteredOrders.value = orders.value.filter(order =>
          order.orderNumber.includes(searchQuery.value) ||
          order.memberName.includes(searchQuery.value)
        )
      }
    }

    const getStatusType = (status) => {
      const statusMap = {
        'PENDING': 'warning',
        'COMPLETED': 'success',
        'CANCELLED': 'danger'
      }
      return statusMap[status] || 'info'
    }

    const getStatusText = (status) => {
      const statusMap = {
        'PENDING': '待处理',
        'COMPLETED': '已完成',
        'CANCELLED': '已取消'
      }
      return statusMap[status] || status
    }

    const viewOrderDetail = (order) => {
      selectedOrder.value = order
      showDetailDialog.value = true
    }

    const completeOrder = async (orderId) => {
      try {
        await ElMessageBox.confirm('确定要完成这个订单吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        const response = await fetch(`/api/orders/${orderId}/complete`, { 
          method: 'PUT' 
        })
        if (response.ok) {
          ElMessage.success('订单已完成')
          loadOrders()
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('操作失败')
        }
      }
    }

    const updateOrderStatus = async (orderId, status) => {
      try {
        const response = await fetch(`/api/orders/${orderId}/status`, {
          method: 'PUT',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ status })
        })

        if (response.ok) {
          ElMessage.success('订单状态更新成功')
          loadOrders()
        }
      } catch (error) {
        ElMessage.error('更新失败')
        // 模拟成功更新
        ElMessage.success('订单状态更新成功')
        loadOrders()
      }
    }

    const deleteOrder = async (id) => {
      try {
        await ElMessageBox.confirm('确定要删除这个订单吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        const response = await fetch(`/api/orders/${id}`, { method: 'DELETE' })
        if (response.ok) {
          ElMessage.success('删除成功')
          loadOrders()
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
          // 模拟成功删除
          ElMessage.success('删除成功')
          loadOrders()
        }
      }
    }

    onMounted(() => {
      loadOrders()
    })

    onUnmounted(() => {
      // 清理组件状态
      loading.value = false
      showDetailDialog.value = false
      selectedOrder.value = null
    })

    return {
      loading,
      orders,
      filteredOrders,
      searchQuery,
      showDetailDialog,
      selectedOrder,
      handleSearch,
      getStatusType,
      getStatusText,
      viewOrderDetail,
      completeOrder,
      updateOrderStatus,
      deleteOrder
    }
  }
}
</script>

<style scoped>
.order-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-bar {
  margin-bottom: 20px;
}

.order-detail {
  padding: 20px;
}

.order-info {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f5f5;
  border-radius: 5px;
}

.order-info h3 {
  margin-top: 0;
  margin-bottom: 15px;
}

.order-info p {
  margin: 5px 0;
}

.order-items {
  margin-bottom: 20px;
}

.order-items h3 {
  margin-bottom: 15px;
}

.order-summary {
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 5px;
  text-align: right;
}

.order-summary p {
  margin: 5px 0;
  font-size: 16px;
}
</style> 